package com.cloud.phone.task;

import android.os.Handler;
import android.os.Looper;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.cloud.phone.constants.Constants;
import com.cloud.phone.service.AccessibilityAutoMainService;
import com.cloud.phone.task.bean.MsgTaskBean;
import com.cloud.phone.task.bean.ServerInnerDataBean;
import com.cloud.phone.task.bean.ServerTaskDataBean;
import com.cloud.phone.task.bean.ServerTaskInnerBean;
import com.cloud.phone.task.taskCongfig.TaskTypeConfig;
import com.cloud.phone.tools.LogUtils;
import com.cloud.phone.tools.MyUtils;
import com.cloud.phone.utils.AccessibilityUtil;
import com.cloud.phone.view.TsUtils;
import com.cloud.phone.websocket.WebsocketUtil;
import com.google.gson.JsonObject;


/**
 * 所有任务类型的基类
 */
public abstract class BaseTask {
    public static final int WAIT = 0;//等待开始
    public static final int ON_START_TASK = 1;//任务开始
    public static final int RUNNING_TASK = 2;//正在执行
    public static final int FINISH = 3;//任务已完成
    public static final int STOP = 4;//任务停止
    public static final int ERR = 5;//任务出错

    public static final int SERVER_STATUS_ERR=3;
    public static final int SERVER_STATUS_FINISH=2;
    public int taskStatus = WAIT;
    public TaskManager taskManager;
    public ServerTaskDataBean serverTaskDataBean;
    public AccessibilityAutoMainService service;
    private long delayTime = 2000;//每个动作间隔时间
    public int currentTaskType=-1000;
    public int lastTaskType;

    public void setServerTaskDataBean(ServerTaskDataBean serverTaskDataBean) {
        this.serverTaskDataBean = serverTaskDataBean;
        setCurrentTaskType(serverTaskDataBean.getTaskType());
    }

    /**
     * 临时停止任务可以直接设置Type=STOP_CURRENT_TASK
     *
     * @param currentTaskType
     */
    public void setCurrentTaskType(int currentTaskType) {
        if (currentTaskType == TaskTypeConfig.STOP_CURRENT_TASK) {
            taskStatus = STOP;
        }
        this.currentTaskType = currentTaskType;
    }

    /**
     * 无需调用，taskManager中会主动设置
     *
     * @param accessibilityService
     */
    public void setAccessibilityService(AccessibilityAutoMainService accessibilityService) {
        this.service = accessibilityService;
    }

    public abstract void doTask() throws InterruptedException;

    public BaseTask() {
        taskManager = TaskManager.getInstance();
    }

    /**
     * 创建task成功后调用将任务添加到任务队列中
     * 存在对应任务的情况下不予替换
     */
    public void addToTaskList() {
        taskManager.tasks.add(this);
    }

    public void delayDo(SomeThing someThing) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    someThing.doSomeThing();
                }
            }, delayTime);
        } else {
            try {
                Thread.sleep(delayTime);
                someThing.doSomeThing();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void delayDo(SomeThing someThing, long delayTime) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    someThing.doSomeThing();
                }
            }, delayTime);
        } else {
            try {
                Thread.sleep(delayTime);
                someThing.doSomeThing();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public interface SomeThing {
        void doSomeThing();
    }


    /**
     * 创建task成功后调用将任务添加到任务队列中
     * 存在对应任务的情况下不予替换
     */
    public void addOrReplaceToTaskList() {
        taskManager.tasks.clear();
        taskManager.tasks.add(this);
    }




    public void showLogAndTsPrint(String msg) {
        LogUtils.v(msg);
        sendLogDataToServer(msg);
        if (Looper.myLooper() != Looper.getMainLooper()) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    TsUtils.showTips(msg);
                }
            });
        } else {
            TsUtils.showTips(msg);
        }

    }

    private void sendLogDataToServer(String msg) {
        MsgTaskBean msgLog = createLogMsgDataBean(msg);
        if(MyUtils.isEmpty(msgLog.getData().getMainId())&&MyUtils.isEmpty(msgLog.getData().getId())){
            //定时任务没有id和mainId不传日志
            return;
        }
        String logStr = GsonUtils.toJson(msgLog);
        WebsocketUtil.getWebsocketUtil().sendMsg(logStr);
    }

    private MsgTaskBean createLogMsgDataBean(String msg) {
        MsgTaskBean msgTaskBean=new MsgTaskBean();
        msgTaskBean.setTaskType(currentTaskType);
        msgTaskBean.setType(1);
        msgTaskBean.setCode(1003);
        msgTaskBean.setToken(SPUtils.getInstance().getString("token"));
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("logMsg",msg);
        ServerInnerDataBean serverInnerDataBean=new ServerInnerDataBean();
        serverInnerDataBean.setJson(GsonUtils.toJson(jsonObject));
        serverInnerDataBean.setId(serverTaskDataBean.getId());
        serverInnerDataBean.setMainId(serverTaskDataBean.getMainId());
        msgTaskBean.setData(serverInnerDataBean);
        return msgTaskBean;
    }


    public void onTaskStop() {
        taskStatus = STOP;
        showLogAndTsPrint("任务已终止");
        if(serverTaskDataBean!=null&&serverTaskDataBean.getId()!=null) {
            MsgTaskManger.showLog("任务终止"+serverTaskDataBean.toString());
            SendMsgUtils.INSTANCE.sendStopTaskMsgBean(serverTaskDataBean.getId());
        }
//        taskManager.tasks.remove(this);
        AccessibilityUtil.killApp(service, Constants.tiktokPackageName);
    }

    public void onTaskResume() {
        showLogAndTsPrint("任务开始");
        delayDo(new SomeThing() {
            @Override
            public void doSomeThing() {
                taskStatus = ON_START_TASK;
            }
        });
    }


    public long lastErrSendTime;
    public void onTaskErr(){
        if(currentTaskType==TaskTypeConfig.STOP_CURRENT_TASK){
            return;
        }
        taskStatus = ERR;
        //防止多处错误时发送多条消息给服务器
        if(System.currentTimeMillis()-lastErrSendTime<1000){
            return;
        }
        lastErrSendTime=System.currentTimeMillis();
        if (currentTaskType >= 2 && currentTaskType <= 11||currentTaskType==13||currentTaskType==15) {
            WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(getBaseMsgData(SERVER_STATUS_ERR)));
        }else if(currentTaskType==TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO&&serverTaskDataBean.getId()!=null){
            WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(getBaseMsgData(SERVER_STATUS_ERR)));
        }
    }


    public void onTaskErr(String errMsg) {
        showLogAndTsPrint("任务出错："+errMsg);
        MsgTaskManger.showLog("任务出错："+errMsg);
        onTaskErr();
    }

    public void onTaskRunning() throws InterruptedException {
        taskStatus = RUNNING_TASK;
    }

    /**
     * 将任务状态改为开始状态--可不断刷新根节点node
     */
    public void changeTaskStatusToStart() {
        if (taskStatus == STOP) {
            LogUtils.i("已停止，需要恢复任务请调用onTaskResume");
            return;
        }
        taskStatus = ON_START_TASK;
    }

    public void onTaskFinish() throws InterruptedException {
        showLogAndTsPrint("任务已完成");
        MsgTaskManger.showLog("任务taskType="+currentTaskType+"已完成");
        if (!taskManager.tasks.isEmpty() && taskManager.tasks.contains(this)) {
            sendSuccessResultToServer();
            taskManager.tasks.remove(this);
            LogUtils.d("任务结束，移除当前任务");
        }
        taskStatus=FINISH;
    }






    /**
     * 在需要给服务端返回任务成功完成结果时调用
     */
    private void sendSuccessResultToServer() {
        if (currentTaskType >= 3 && currentTaskType <= 11||currentTaskType==13||currentTaskType==15) {
            LogUtils.v("任务完成，回传消息给服务器");
            WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(getBaseMsgData(SERVER_STATUS_FINISH)));
        }else if(currentTaskType==TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO&&serverTaskDataBean.getId()!=null){
            WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(getBaseMsgData(SERVER_STATUS_FINISH)));
        }
    }


    /**
     * int TIKTOK_AUTO_LOOK_VIDEO=3;//自动养号
     * int TIKTOK_SEARCH_AUTO_LOOK_VIDEO=4;//搜索关键字并自动养号
     * int TIKTOK_TASK_ATTENTION_USER =5;//关注用户
     * int TIKTOK_TASK_GET_USER_FAN_LIST = 6;//获取用户粉丝列表
     * int TIKTOK_TASK_SINGLE_WORKS_LIKE_BY_LINK = 7;//根据链接进行作品点赞
     * int TIKTOK_TASK_SINGLE_WORKS_COMMENT_BY_LINK = 8;//根据链接进行作品评论
     * int TIKTOK_TASK_SINGLE_CHAT_TO_USER = 9;//主动私信单个用户
     * int TIKTOK_TASK_CHANGE_PERSONAL_INFO = 10;//修改资料
     * int TIKTOK_TASK_AUTO_PUBLISH_WORKS = 11;//自动发布作品
     *
     * @return
     */
    public int getServerTaskTypeByCurrentTaskType() {
        int serverTaskType=currentTaskType;
        switch (currentTaskType) {
            case TaskTypeConfig.TIKTOK_AUTO_LOOK_VIDEO:
            case TaskTypeConfig.TIKTOK_SEARCH_AUTO_LOOK_VIDEO:
                serverTaskType=TaskTypeConfig.SERVER_TASK_KEEP_ACCOUNT;
                break;
            case TaskTypeConfig.TIKTOK_TASK_ATTENTION_USER:
                serverTaskType=TaskTypeConfig.SERVER_TASK_ATTENTION_SINGLE_USER;
                break;
            case TaskTypeConfig.TIKTOK_TASK_GET_USER_FAN_LIST:
                break;
            case TaskTypeConfig.TIKTOK_TASK_SINGLE_WORKS_LIKE_BY_LINK:
                serverTaskType=TaskTypeConfig.SERVER_TASK_LIKE_SINGLE_WORK;
                break;
            case TaskTypeConfig.TIKTOK_TASK_SINGLE_WORKS_COMMENT_BY_LINK:
                serverTaskType=TaskTypeConfig.SERVER_TASK_COMMENT_SINGLE_WORK;
                break;
            case TaskTypeConfig.TIKTOK_TASK_SINGLE_CHAT_TO_USER:
                serverTaskType=TaskTypeConfig.SERVER_SEND_MSG;
                break;
            case TaskTypeConfig.TIKTOK_TASK_GET_CHAT_TO_USER_FANS_LIST:
                serverTaskType=TaskTypeConfig.SERVER_GET_USER_FANS_TO_CHAT_LIST;
                break;
            case TaskTypeConfig.TIKTOK_TASK_CHANGE_PERSONAL_INFO:
                serverTaskType=TaskTypeConfig.SERVER_TASK_EDIT_USER_INFO;
                break;
            case TaskTypeConfig.TIKTOK_TASK_AUTO_PUBLISH_WORKS:
                serverTaskType=TaskTypeConfig.SERVER_TASK_PUBLISH_WORKS;
                break;
            default:
                serverTaskType=currentTaskType;
                break;
        }
        return serverTaskType;
    }


    private MsgTaskBean getBaseMsgData(int taskStatus) {
        MsgTaskBean msgTaskBean = new MsgTaskBean();
        msgTaskBean.setCode(1006);
        msgTaskBean.setToken(SPUtils.getInstance().getString("token"));
        msgTaskBean.setTaskType(getServerTaskTypeByCurrentTaskType());
        ServerTaskInnerBean resultInnerBean = new ServerTaskInnerBean();
        if(currentTaskType==TaskTypeConfig.TIKTOK_TASK_AUTO_LOGIN||currentTaskType==TaskTypeConfig.TIKTOK_TASK_AUTO_REGISTER){
            resultInnerBean.setAccountId(serverTaskDataBean.getAccountId());
            resultInnerBean.setNickName(serverTaskDataBean.getNickName());
            resultInnerBean.setFans(serverTaskDataBean.getFans());
            resultInnerBean.setLike(serverTaskDataBean.getLike());
            resultInnerBean.setAttention(serverTaskDataBean.getAttention());
            resultInnerBean.setProfile(serverTaskDataBean.getProfile());
            if(currentTaskType==TaskTypeConfig.TIKTOK_TASK_AUTO_LOGIN) {
                msgTaskBean.setType(16);
            }
        }
        resultInnerBean.setTaskType(getServerTaskTypeByCurrentTaskType());
        ServerInnerDataBean serverInnerDataBean=new ServerInnerDataBean();
        serverInnerDataBean.setJson(GsonUtils.toJson(resultInnerBean));
        serverInnerDataBean.setStatus(taskStatus);
        serverInnerDataBean.setId(serverTaskDataBean.getId());
        serverInnerDataBean.setMainId(serverTaskDataBean.getMainId());
        msgTaskBean.setData(serverInnerDataBean);
        return msgTaskBean;
    }


    @Override
    public String toString() {
        return "BaseTask{" +
                "taskStatus=" + taskStatus +
                ", taskManager=" + taskManager +
                ", serverTaskDataBean=" + serverTaskDataBean +
                ", service=" + service +
                ", delayTime=" + delayTime +
                ", currentTaskType=" + currentTaskType +
                ", lastTaskType=" + lastTaskType +
                '}';
    }
}
